from django.http import JsonResponse
from drf_spectacular.utils import extend_schema
from rest_framework.decorators import action
from rest_framework.mixins import (CreateModelMixin, ListModelMixin,
                                   RetrieveModelMixin, UpdateModelMixin)
from rest_framework.viewsets import GenericViewSet
from utils.autoschema import AutoDocSchema, custom_response_serailizer
from utils.decorators import error_response, request_data
from backend.cews.models import Imte, RepairOrder, RepairOrderTask, RepairOrderTaskImte

from .serializers import (ImteSerializer)


class ImteViewSet(
    RetrieveModelMixin,
    ListModelMixin,
    UpdateModelMixin,
    GenericViewSet,
    CreateModelMixin
):
    serializer_class = ImteSerializer
    queryset = Imte.objects.all()

    @extend_schema(responses=custom_response_serailizer(ImteSerializer(many=True)))
    @action(detail=False, methods=['get'], schema=AutoDocSchema())
    @request_data(keys=['wo'],request_attr='GET')
    def get_imte_by_repair_order(self,request,wo):
        '''
            desc: 
                Get list of repair order task for a repair order \n\n
                ``wo means repair_order_id``
        '''
        try:
            repair_order = RepairOrder.objects.get(id=wo)
            rot = RepairOrderTask.objects.filter(repair_order=repair_order)
            imte_ids = RepairOrderTaskImte.objects.filter(repair_order_task__in=rot).values_list('imte',flat=True)
            data = Imte.objects.filter(id__in=imte_ids)
            
            return JsonResponse(data={
                'code':1,
                'data':ImteSerializer(data,many=True).data
            },status=200)
        except (RepairOrder.DoesNotExist,RepairOrder.MultipleObjectsReturned) as ex:
            return JsonResponse(data={
                'code':0,
                'message':str(ex),
            },status=400)
            
    @extend_schema(responses=custom_response_serailizer(ImteSerializer(many=True)))
    @action(detail=False, methods=['get'], schema=AutoDocSchema(),url_name='get_imte_by_eform_id')
    @request_data(keys=['eform_id'],request_attr='GET')
    def get_imte_by_eform_id(self,request,eform_id):
        '''
            desc: 
                Get list of repair order task for a repair order \n\n
                ``wo means repair_order_id``
        '''
        try:
            rot = RepairOrderTask.objects.filter(eform_id=eform_id)
            imte_ids = RepairOrderTaskImte.objects.filter(repair_order_task__in=rot).values_list('imte',flat=True)
            data = Imte.objects.filter(id__in=imte_ids)
            return JsonResponse(data={
                'code':1,
                'data':ImteSerializer(data,many=True).data
            },status=200)
        except (RepairOrder.DoesNotExist,RepairOrder.MultipleObjectsReturned) as ex:
            return JsonResponse(data={
                'code':0,
                'message':str(ex),
            },status=400)
    
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=['imte_no','eform_id','due_date','imte_type'])
    @error_response(ValueError,Imte.DoesNotExist)
    def set_imte_to_task(self,request,imte_no,eform_id,due_date,imte_type):
        try:
            imte = Imte.objects.get(imte_no=imte_no)
        except Imte.DoesNotExist:
            raise ValueError('Imte not found')
        
        # ## check is exisit
        # imte_task = RepairOrderTaskImte.objects.filter(imte=imte)
        
        ## find repair order task by eform_id
        rot = RepairOrderTask.objects.filter(eform_id=eform_id).first()
        
        # if imte_task:
        #     raise ValueError('Imte already scanned for the task')
        
        if not rot:
            raise ValueError('RepairOrderTask not found')
        
        # imte = models.ForeignKey(Imte, on_delete=models.CASCADE)
        # repair_order_task = models.ForeignKey(RepairOrderTask, on_delete=models.CASCADE)
        # due_date = models.DateField("DUE_DATE", blank=True, null=True)
        # equipment = models.CharField("EQUIPMENT", max_length=200, blank=True, null=True)
        # imte_no = models.CharField("IMTE_NO", max_length=200, blank=True, null=True)
        # created_on = models.DateTimeField(auto_now_add=True)
        
        # check is exisit 
        if RepairOrderTaskImte.objects.filter(imte=imte,repair_order_task=rot).first():
            raise ValueError('Imte already scanned')
        
        roti = RepairOrderTaskImte.objects.create(
            imte = imte,
            repair_order_task=rot,
            imte_type = imte.imte_type,
            due_date = imte.due_date,
            equipment = imte.equipment,
            imte_no = imte.imte_no,
        )
        
        return JsonResponse(data={
            'code':1,
            'message':'Success',
        },status=200)
    
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=['imte_no','eform_id'])
    @error_response()
    def delete_imte_from_task(self,request,imte_no,eform_id):
        
        rot= RepairOrderTask.objects.filter(eform_id=eform_id).first()
        
        if not rot:
            raise ValueError('RepairOrderTask not found')
        
        ## check is exisit
        imte_task = RepairOrderTaskImte.objects.filter(repair_order_task=rot,imte_no=imte_no).first()

        
        if not imte_task:
            raise ValueError('Imte not found')
        
        ## delete
        imte_task.delete()
        
        return JsonResponse(data={
            'code':1,
            'message':'Success',
        },status=200)